package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LMessage;
import com.learn.core.domain.LMessageUser;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.dto.LMessageDTO;
import com.learn.core.service.ILMessageService;
import com.learn.core.service.ILMessageUserService;
import com.learn.core.service.IUserDetailsGatherService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LMessageController
 * @date 2021.06.22 09:07
 */
@Api("消息")
@RestController
@RequestMapping("/manager/message")
public class LMessageController extends WebController<LMessage> {

    @Autowired
    ILMessageService ilMessageService;
    @Autowired
    ILMessageUserService ilMessageUserService;
    @Autowired
    IUserDetailsGatherService iUserDetailsGatherService;

    //消息列表
    @ApiOperation(value = "消息列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LMessage> list(@RequestBody LMessageDTO lMessageDTO){
        try {
            if(lMessageDTO==null||lMessageDTO.getPage()==null||lMessageDTO.getRows()==null){
                return new PageResult<LMessage>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lMessageDTO.getPage(),lMessageDTO.getRows());
            QueryWrapper<LMessage> queryWrapper = new QueryWrapper<LMessage>();
            if (StringUtils.isNotEmpty(lMessageDTO.getState()))
                queryWrapper.eq("message_state",lMessageDTO.getState());
            if(StringUtils.isNotEmpty(lMessageDTO.getMessageType()))
                queryWrapper.eq("message_type",lMessageDTO.getMessageType());
            queryWrapper.orderByDesc("create_time");
            Page<LMessage> lMessages = (Page<LMessage>) ilMessageService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lMessages)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lMessages.getTotal(), lMessages, ResultEnum.SUCCESS);
        }catch (Exception e){
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新消息信息", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LMessage lMessage) {
        if(lMessage!=null){
            LMessage message = ilMessageService.getById(lMessage.getMessageId());
            if("1".equals(message.getMessageState())){
                if(ilMessageService.updateById(lMessage))
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
            }
            return (CommonResult) ResultUtil.error(ResultEnum.NOT_MESSAGE_STATE);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加消息", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LMessage lMessage, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lMessage!=null) {
                if (StringUtils.isEmpty(lMessage.getMessageContent()))
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_MESSAGE_COUTENT);
                if (StringUtils.isEmpty(lMessage.getMessageType()))
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_MESSAGE_TYPE);
                lMessage.setCreateTime(new Date());
                lMessage.setCreateUser(userId);
                lMessage.setMessageState("1");
                if (ilMessageService.save(lMessage))
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除消息", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LMessage lMessage){
        try {
            if(lMessage!=null){
                if(lMessage.getMessageId()!=null){
                    LMessage message = ilMessageService.getById(lMessage.getMessageId());
                    if("2".equals(message.getMessageState())){
                        return (CommonResult)ResultUtil.error(ResultEnum.NOT_MESSAGE_STATE);
                    }
                    QueryWrapper<LMessage> queryWrapper = new QueryWrapper<LMessage>();
                    queryWrapper.in(true, "message_id", lMessage.getMessageId());
                    if(ilMessageService.remove(queryWrapper))
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //发布
    @ApiOperation(value = "发布")
    @GetMapping("/release")
    @UserLoginToken
    @Log(title = "发布消息", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> release(@RequestParam("id")Integer id) {
        if(id!=null){
            LMessage lMessage = new LMessage();
            lMessage.setMessageId(id);
            lMessage.setCreateTime(new Date());
            lMessage.setMessageState("2");
            if(ilMessageService.updateById(lMessage)) {
                LMessage message = ilMessageService.getById(lMessage.getMessageId());
                if(null != message){
                    String messageObject = message.getMessageObject();
                    String [] org = messageObject.split(",");
                    for (String organ : org) {
                        QueryWrapper<UserDetailsGather> queryWrapper = new QueryWrapper<UserDetailsGather>();
                        queryWrapper.eq("organization_id",organ);
                        List<UserDetailsGather> list = iUserDetailsGatherService.list(queryWrapper);
                        for (UserDetailsGather user: list) {
                            LMessageUser lMessageUser = new LMessageUser();
                            lMessageUser.setUserId(user.getUserId());
                            lMessageUser.setMessageId(id);
                            lMessageUser.setState("1");
                            ilMessageUserService.save(lMessageUser);
                        }
                    }
                }
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}
